<!--
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-07-18 09:48:48
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-07-26 12:09:52
 * @FilePath: \HuiLin\pages\homePages\cleaningOrderHistory.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<view class="order-history-page">
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header_slot flex justify-start align-center" @click="closePage()">
					<view class="action back-btn">
						<text class="cuIcon-back "></text>
					</view>
					<view class="content text-bold">
						保洁历史订单
					</view>
				</view>
			</template>
		</headerSlot>
		<view class="content-area">
			<view v-if="orders.length === 0" class="empty">暂无历史订单</view>
			<view v-else>
				<view v-for="(item, idx) in orders" :key="idx" class="order-item">
					<view class="flex justify-between align-center" style="margin-bottom: 10rpx;">
						<view style="font-size: 16px;font-weight: 700;">{{item.typeId.name}}</view>
						<view class="cu-tag bg-green">{{setStatus(item.currentStatus || item.status)}}</view>
					</view>
					<view class="order-addr">订单编号：{{item.orderNo || item._id}}</view>
					<view class="order-addr">订单价格： <text style="color: red;">￥{{item.payAmount || item.typeId.price}}</text> </view>
					<view class="order-addr">支付状态： <text :style="{color: getPayStatusColor(item.payStatus)}">{{getPayStatusText(item.payStatus)}}</text> </view>
					<view class="order-addr">预约时间：{{formatTime(item.dateTime)}}</view>
					<view class="order-addr">地址：{{item.address}}</view>
					<view class="order-remark">备注：{{item.remark || '无'}}</view>
					<view v-if="(item.currentStatus || item.status)==='cancelled' && item.cancelReason" class="order-cancel-reason">
						取消原因：{{item.cancelReason}}</view>
					<view v-if="item.comment" class="order-comment">
						<view class="flex justify-between align-center">
							<view class="flex align-center">
								评分:<uni-rate :value="item.rating" readonly size="18" />
							</view>
							<text class="comment-time">{{formatTime(item.commentAt)}}</text>
						</view>
						<view class="comment-content">{{item.comment}}</view>
					</view>
					<view class="flex justify-end" style="margin-top: 16rpx;">
						<button v-if="item.payStatus==='unpaid' && (item.currentStatus || item.status)==='pending'" class="cu-btn bg-blue margin-right-sm"
							@click="rePay(item._id)">重新支付</button>
						<button v-if="(item.currentStatus || item.status)==='pending'" class="cu-btn bg-red margin-right-sm"
							@click="openCancel(item._id)">取消订单</button>
						<button v-if="(item.currentStatus || item.status)==='completed' && !item.comment" class="cu-btn bg-orange"
							@click="openComment(item._id)">评价</button>
					</view>
				</view>
			</view>
			<!-- 取消订单弹窗 -->
			<uni-popup ref="cancelPopup" type="dialog">
				<view class="popup-content">
					<view class="popup-title">取消订单</view>
					<textarea v-model="cancelReason" placeholder="请输入取消原因" class="popup-textarea" />
					<view class="popup-actions">
						<button class="cu-btn margin-right-sm" @click="closeDialog">关闭</button>
						<button class="cu-btn bg-red" @click="confirmCancel">确认取消</button>
					</view>
				</view>
			</uni-popup>
			<!-- 评价订单弹窗 -->
			<uni-popup ref="commentPopup" type="dialog">
				<view class="popup-content">
					<view class="popup-title">订单评价</view>
					<view class="flex align-center" style="margin-bottom: 16rpx;">
						<text>评分：</text>
						<uni-rate v-model="commentRating" :max="5" allow-half />
					</view>
					<textarea v-model="commentText" placeholder="请输入评价内容" class="popup-textarea" />
					<view class="popup-actions">
						<button class="cu-btn margin-right-sm" @click="closeDialog">关闭</button>
						<button class="cu-btn bg-orange" @click="confirmComment">提交评价</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>
<script>
	import headerSlot from '@/components/header-slot.vue';
	import {
		getRepairServiceOrderHistory,
		cancelRepairServiceOrder,
		commentRepairServiceOrder
	} from '@/api/order.js';
	import RepairServicePayment from '@/utils/RepairServicePayment.js';
	export default {
		name: 'CleaningOrderHistory',
		components: {
			headerSlot
		},
		data() {
			return {
				orders: [],
				page: 1,
				hasMore: true,
				loading: false,
				showCancelDialog: false,
				showCommentDialog: false,
				currentOrderId: '',
				cancelReason: '',
				commentRating: 5,
				commentText: '',
				pagination: {
					page: 1,
					limit: 10,
				},
				noMoreData: false,
				paymentHandler: new RepairServicePayment(),
				isRepaying: false
			}
		},
		onLoad() {
			this.getOrders();
		},
		onPullDownRefresh() {
			this.resetList();
			this.getOrders();
		},
		onReachBottom() {
			if (!this.noMoreData) {
				this.pagination.page++;
				this.getOrders();
			}
		},
		onUnload() {
			// 页面卸载时停止所有轮询
			if (this.paymentHandler) {
				this.paymentHandler.stopAllPolling();
			}
		},
		methods: {
			resetList() {
				this.orders = [];
				this.pagination.page = 1;
				this.noMoreData = false;
			},
			setStatus(status) {
				let STATUSOBJ = {
					'pending': '待服务',
					'accepted': '已接单',
					'completed': '已完成',
					'cancelled': '已取消',
					// 可能的中文状态值
					'待服务': '待服务',
					'已接单': '已接单',
					'已完成': '已完成',
					'已取消': '已取消',
					// 可能的数字状态值
					0: '待服务',
					1: '已接单',
					2: '已完成',
					3: '已取消'
				}

				return STATUSOBJ[status] || '未知状态'
			},
			getPayStatusText(payStatus) {
				const statusMap = {
					'unpaid': '未支付',
					'paid': '已支付',
					'refunded': '已退款'
				};
				return statusMap[payStatus] || '未知';
			},
			getPayStatusColor(payStatus) {
				const colorMap = {
					'unpaid': '#ff6b35',
					'paid': '#28a745',
					'refunded': '#6c757d'
				};
				return colorMap[payStatus] || '#666';
			},
			async getOrders() {
				this.loading = true;
				try {
					const res = await getRepairServiceOrderHistory({
						category: 'cleaning',
						page: this.pagination.page,
						limit: this.pagination.limit
					});
					if (res.data.code === 200) {
						const newOrders = res.data.data.list || [];
						if (this.pagination.page === 1) {
							this.orders = newOrders;
						} else {
							this.orders = [...this.orders, ...newOrders];
						}
						
						// 判断是否还有更多数据
						const total = res.data.data.pagination.total;
						const currentTotal = this.orders.length;
						this.noMoreData = currentTotal >= total;
						
						if (newOrders.length === 0 && this.pagination.page > 1) {
							this.pagination.page--;
						}
					} else {
						uni.showToast({
							title: res.data.message || '获取订单失败',
							icon: 'none'
						});
					}
				} catch (e) {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					uni.stopPullDownRefresh();
				}
			},
			closePage() {
				uni.navigateBack();
			},
			openCancel(orderId) {
				this.currentOrderId = orderId;
				this.cancelReason = '';
				this.$refs.cancelPopup.open();
			},
			async confirmCancel() {
				if (!this.cancelReason) {
					uni.showToast({
						title: '请填写取消原因',
						icon: 'none'
					});
					return;
				}
				try {
					const res = await cancelRepairServiceOrder(this.currentOrderId, this.cancelReason);
					if (res.data.code === 200) {
						uni.showToast({
							title: '已取消',
							icon: 'success'
						});
						this.resetList();
						this.getOrders();
					} else {
						uni.showToast({
							title: res.data.message || '取消失败',
							icon: 'none'
						});
					}
				} catch (e) {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
				this.closeDialog();
			},
			openComment(orderId) {
				this.currentOrderId = orderId;
				this.commentRating = 5;
				this.commentText = '';
				this.$refs.commentPopup.open();
			},
			async confirmComment() {
				if (!this.commentText) {
					uni.showToast({
						title: '请填写评价内容',
						icon: 'none'
					});
					return;
				}
				try {
					const res = await commentRepairServiceOrder(this.currentOrderId, {
						rating: this.commentRating,
						comment: this.commentText
					});
					if (res.data.code === 200) {
						uni.showToast({
							title: '评价成功',
							icon: 'success'
						});
						this.resetList();
						this.getOrders();
					} else {
						uni.showToast({
							title: res.data.message || '评价失败',
							icon: 'none'
						});
					}
				} catch (e) {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
				this.closeDialog();
			},
			closeDialog() {
				this.$refs.cancelPopup.close();
				this.$refs.commentPopup.close();
			},
			loadMore() {
				this.getOrders(true);
			},
			async rePay(orderId) {
				if (this.isRepaying) {
					uni.showToast({
						title: '正在处理中，请稍候',
						icon: 'none'
					});
					return;
				}
				
				// 找到对应的订单信息
				const order = this.orders.find(item => item._id === orderId);
				if (!order) {
					uni.showToast({
						title: '订单信息不存在',
						icon: 'none'
					});
					return;
				}
				
				this.isRepaying = true;
				uni.showLoading({
					mask: true,
					title: '发起支付中...'
				});
				
				try {
					// 使用支付处理器处理重新支付
					await this.paymentHandler.processPayment(
						{
							typeId: order.typeId._id,
							dateTime: order.dateTime,
							address: order.address,
							remark: order.remark
						},
						// 支付成功回调
						(orderId, result) => {
							uni.hideLoading();
							uni.showToast({
								title: '支付成功！',
								icon: 'success'
							});
							
							// 刷新订单列表
							setTimeout(() => {
								this.resetList();
								this.getOrders();
							}, 1500);
						},
						// 支付失败回调
						(orderId, error) => {
							uni.hideLoading();
							uni.showToast({
								title: error.message || '支付失败',
								icon: 'none'
							});
						},
						// 支付超时回调
						(orderId) => {
							uni.hideLoading();
							uni.showToast({
								title: '支付状态查询超时，请稍后手动检查',
								icon: 'none'
							});
						}
					);
					
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: error.message || '支付失败',
						icon: 'none'
					});
				} finally {
					this.isRepaying = false;
				}
			},
			formatTime(utcTimeString) {
				if (!utcTimeString) return false;
				const now = new Date(),
					inputDate = new Date(utcTimeString);
				const nowDate = now.getDate(),
					inputDateDate = inputDate.getDate();
				let dayLabel = "";
				if (nowDate === inputDateDate) {
					dayLabel = "今天 ";
				} else if (nowDate - inputDateDate === 1) {
					dayLabel = "昨天 ";
				} else if (nowDate - inputDateDate === -1) {
					dayLabel = "明天 ";
				}
				const weekday = inputDate.toLocaleDateString('zh-CN', { weekday: 'short' });
				const hours = inputDate.getHours().toString().padStart(2, '0');
				const minutes = inputDate.getMinutes().toString().padStart(2, '0');
				const time = `${hours}:${minutes}`;
				return dayLabel ? `${dayLabel}${weekday} ${time}` : `${weekday} ${time}`;
			}
		}
	}
</script>
<style scoped>
	.order-history-page {
		min-height: 100vh;
		background: #f8f8f8;
	}

	.header_slot {
		padding: 0 32rpx;
		width: 100%;
		font-weight: 500;
		font-size: 36rpx;
		color: #2C2622;
	}

	.back-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
	}

	.content-area {
		padding: 40rpx 24rpx;
	}

	.order-item {
		background: #fff;
		border-radius: 12rpx;
		margin-bottom: 32rpx;
		padding: 32rpx;
		box-shadow: 0 4rpx 16rpx #fd6e3711;
	}

	.order-title {
		font-size: 30rpx;
		font-weight: 700;
		color: #fd6e37;
		margin-bottom: 12rpx;
	}

	.order-addr,
	.order-remark {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 6rpx;
	}

	.empty {
		text-align: center;
		color: #bbb;
		font-size: 28rpx;
		margin-top: 80rpx;
	}

	.popup-content {
		padding: 32rpx;
		background: #fff;
		border-radius: 12rpx;
		min-width: 500rpx;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: 700;
		margin-bottom: 24rpx;
	}

	.popup-textarea {
		width: 100%;
		min-height: 100rpx;
		border: 1px solid #eee;
		border-radius: 8rpx;
		padding: 16rpx;
		margin-bottom: 24rpx;
		font-size: 28rpx;
	}

	.popup-actions {
		display: flex;
		justify-content: flex-end;
	}

	.order-cancel-reason {
		color: #e64340;
		font-size: 26rpx;
		margin-top: 8rpx;
	}

	.order-comment {
		background: #f9f9f9;
		border-radius: 8rpx;
		padding: 16rpx;
		margin-top: 12rpx;
	}

	.comment-label {
		color: #fd6e37;
		font-weight: 700;
		margin-right: 8rpx;
	}

	.comment-rating {
		color: #e64340;
		margin-left: 8rpx;
		font-size: 24rpx;
	}

	.comment-time {
		color: #bbb;
		font-size: 22rpx;
	}

	.comment-content {
		color: #333;
		margin-top: 8rpx;
		font-size: 26rpx;
	}
</style>